package com.lunker.moneyrecord;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Settings extends ListActivity implements OnItemClickListener, OnClickListener {
	
	private SharedPreferences config;
	private SettingsListAdapter adapter = null;
	private Dialog fileSelecter = null;
	private Dialog pwdCollecter = null;
	private ArrayList<SettingsItem> data = new ArrayList<SettingsItem>();
	public static final int TAG_IMPORT_DATABASE = 0;
	public static final int TAG_EXPORT_DATABASE = 1;
	public static final int TAG_EXPORT_CSV = 2;
	public static final int TAG_USE_PASSWORD = 3;
	public static final int TAG_SET_PASSWORD = 4;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		config = this.getSharedPreferences("Settings", Context.MODE_PRIVATE);
		
		String titles[] = getResources().getStringArray(R.array.setting_titles);
		String descriptions[] = getResources().getStringArray(R.array.setting_descriptions);
		
		// Initialize items of settings.
		data.add(new SettingsItem(
				SettingsItem.TYPE_TEXT, 
				TAG_IMPORT_DATABASE, 
				titles[TAG_IMPORT_DATABASE], 
				descriptions[TAG_IMPORT_DATABASE]));
		data.add(new SettingsItem(
				SettingsItem.TYPE_TEXT, 
				TAG_EXPORT_DATABASE, 
				titles[TAG_EXPORT_DATABASE], 
				descriptions[TAG_EXPORT_DATABASE]));
		data.add(new SettingsItem(
				SettingsItem.TYPE_TEXT, 
				TAG_EXPORT_CSV, 
				titles[TAG_EXPORT_CSV], 
				descriptions[TAG_EXPORT_CSV]));
		data.add(new SettingsItem(
				SettingsItem.TYPE_BOOLEAN, 
				TAG_USE_PASSWORD, 
				titles[TAG_USE_PASSWORD], 
				descriptions[TAG_USE_PASSWORD]));
		data.add(new SettingsItem(
				SettingsItem.TYPE_TEXT, 
				TAG_SET_PASSWORD, 
				titles[TAG_SET_PASSWORD], 
				descriptions[TAG_SET_PASSWORD]));
		adapter = new SettingsListAdapter(this, R.layout.settings_item, data);
		this.setListAdapter(adapter);
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {		
		switch (adapter.getItem(position).tag) {
		case TAG_IMPORT_DATABASE:
			//restore
			if (fileSelecter == null) {
				fileSelecter = new Dialog(this);
				fileSelecter.setContentView(R.layout.file_selection_dialog);
				fileSelecter.setTitle(getString(R.string.select_a_backup));
				((ListView) fileSelecter.findViewById(R.id.listview_fileSelector_fileList))
						.setOnItemClickListener(this);
				((Button) fileSelecter.findViewById(R.id.btn_fileSelector_cancel))
						.setOnClickListener(this);
			} 
			
			//Get a list of files in SD card.
			String state = Environment.getExternalStorageState();
			
			if (state.equals(Environment.MEDIA_MOUNTED) ||
					state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
				File sdDir = Environment.getExternalStorageDirectory();
				String fNames[] = sdDir.list(new FilenameFilter() {
					
					@Override
					public boolean accept(File dir, String filename) {
						File f = new File(dir, filename);
						if (filename.endsWith(".db") && f.isFile()) {
							return true;
						} else {
							return false;
						}
					}
				});
				ArrayAdapter<String> aa = new ArrayAdapter<String>(
						this,
						R.layout.file_selection_dialog_item,
						R.id.textview_fileSelector_listItem,
						fNames);
				((ListView) fileSelecter.findViewById(R.id.listview_fileSelector_fileList))
						.setAdapter(aa);
				fileSelecter.show();
			} else {
				Toast.makeText(this, getString(R.string.sdcard_is_not_available), 
						Toast.LENGTH_SHORT).show();
			}
			break;
		case TAG_EXPORT_DATABASE:
			//backup
			new ExportDatabaseTask(this).execute();
			break;
		case TAG_EXPORT_CSV:
			//export CSV
			new ExportCSVTask(this).execute();
			break;
		case TAG_USE_PASSWORD:
			//Set using password.
			boolean checked = config.getBoolean(Integer.toString(TAG_USE_PASSWORD), false);
			SharedPreferences.Editor refEditor = config.edit();
			refEditor.putBoolean(Integer.toString(TAG_USE_PASSWORD), !checked);
			refEditor.commit();
			((CheckBox) v.findViewById(R.id.checkbox_setting_value)).setChecked(!checked);
			getListView().invalidate(); //Update enable/disable state.
			break;
		case TAG_SET_PASSWORD:
			//Set password.
			if (pwdCollecter == null) {
				pwdCollecter = new Dialog(this);
				pwdCollecter.setContentView(R.layout.set_password_dialog);
				pwdCollecter.setTitle(getString(R.string.set_the_password));
				((Button) pwdCollecter.findViewById(R.id.btn_setPasswordYes))
						.setOnClickListener(this);
				((Button) pwdCollecter.findViewById(R.id.btn_setPasswordNo))
						.setOnClickListener(this);
			}
			
			((EditText)pwdCollecter.findViewById(R.id.edittext_password_1)).setText(null);
			((EditText)pwdCollecter.findViewById(R.id.edittext_password_2)).setText(null);
			pwdCollecter.show();
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> av, View view, int position, long id) {
		//Listen for fileSelecter.
		fileSelecter.dismiss();	
		String fName = ((TextView) view.findViewById(R.id.textview_fileSelector_listItem))
				.getText().toString();
		new ImportDatabaseTask(this, fName).execute();
	}

	@Override
	public void onClick(View v) {
		//Listen for all dialog buttons.
		switch(v.getId()) {
		case R.id.btn_fileSelector_cancel:
			fileSelecter.dismiss();
			break;
		case R.id.btn_setPasswordNo:
			pwdCollecter.dismiss();
			break;
		case R.id.btn_setPasswordYes:			
			String pwd1 = ((EditText) pwdCollecter.findViewById(R.id.edittext_password_1))
					.getText().toString();
			String pwd2 = ((EditText) pwdCollecter.findViewById(R.id.edittext_password_2))
					.getText().toString();
			if (pwd1 != null && pwd1.equals(pwd2)) {
				pwdCollecter.dismiss();
				SharedPreferences.Editor editor = config.edit();
				editor.putString("password", pwd1);
				editor.commit();
				Toast.makeText(this, getString(R.string.done_setting_the_password), 
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(this, getString(R.string.two_passwords_are_different), 
						Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	private class SettingsListAdapter extends ArrayAdapter<SettingsItem> {
		private LayoutInflater lif = null;

		public SettingsListAdapter(Context context, int textViewResourceId, List<SettingsItem> objects) {
			super(context, textViewResourceId, objects);
			lif = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			
			if (convertView == null) {
				convertView = lif.inflate(R.layout.settings_item, parent, false);
				holder = new ViewHolder();
				holder.title = (TextView) convertView.findViewById(R.id.textview_setting_title);
				holder.descr = (TextView) convertView.findViewById(R.id.textview_setting_description);
				holder.value = (CheckBox) convertView.findViewById(R.id.checkbox_setting_value);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			
			SettingsItem item = getItem(position);
			
			if (item != null) {
				holder.title.setText(item.title);
				holder.descr.setText(item.descr);
				
				if (item.type == SettingsItem.TYPE_BOOLEAN) {
					holder.value.setVisibility(View.VISIBLE);
					holder.value.setChecked(config.getBoolean(Integer.toString(item.tag), false));
				} else {
					holder.value.setVisibility(View.GONE);
				}
			}
			
			return convertView;
		}

		@Override
		public boolean areAllItemsEnabled() {
			return false;
		}

		@Override
		public boolean isEnabled(int position) {
			boolean rtn = true;
			
			switch (getItem(position).tag) {
				case TAG_SET_PASSWORD:
					rtn = config.getBoolean(Integer.toString(TAG_USE_PASSWORD), false);					
					break;
			}
			
			return rtn;
		}
	}
	
	private class SettingsItem {
		
		public static final int TYPE_BOOLEAN = 0;
		public static final int TYPE_TEXT = 1;
		public int type = TYPE_TEXT; //Default
		public String title = null;
		public String descr = null;
		public int tag = -1; //Identity for each setting item. 
		
		public SettingsItem (int type, int tag, String title, String desc) {
			this.type = type;
			this.tag = tag;
			this.title = title;
			this.descr = desc;
		}
		
	}
	
	private class ViewHolder {
		
		public TextView title;
		public TextView descr;
		public CheckBox value;		
	}
}
